/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FilterChainDialog.java
 *
 * Created on 23/01/2009, 10:44:24
 */

package ar.com.umibe.core.filter;

import ar.com.umibe.commons.util.GuiUtils;
import ar.com.umibe.commons.util.UmibeFileUtils;
import ar.com.umibe.core.DataModel;
import ar.com.umibe.gui.FilterTable;

import java.awt.Frame;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.DefaultListModel;
import javax.swing.table.DefaultTableModel;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import wox.serial.Easy;

/**
 *
 * @author Usuario
 */
public class FilterChainDialog extends javax.swing.JDialog {

    private boolean initialized = false;
	/** Creates new form FilterChainDialog */
    public FilterChainDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        loadFilters();
		GuiUtils.centerOnScreen(this);
		GuiUtils.setIcon(this);
        initialized = true;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new FilterTable();
        jToggleButton1 = new javax.swing.JToggleButton();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jComboBox2 = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N


        jTable1.setName("jTable1"); // NOI18N
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable1KeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 314, Short.MAX_VALUE)
        );

        jToggleButton1.setText("Generate profile");
        jToggleButton1.setName("jToggleButton1"); // NOI18N
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });

        jTextField1.setText("Default");
        jTextField1.setName("jTextField1"); // NOI18N

        jButton1.setText("Cancel");
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jComboBox2.setName("jComboBox2"); // NOI18N
        jComboBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox2ActionPerformed(evt);
            }
        });

        jLabel1.setText("Add filter");
        jLabel1.setName("jLabel1"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jToggleButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jToggleButton1)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
        saveProfile();
        this.setVisible(false);
}//GEN-LAST:event_jToggleButton1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
    	if(initialized  == true){
    		try {
    			Filter f = (Filter) Easy.load("./filters/" + (String)jComboBox2.getSelectedItem());
    			Object[] params = { new Frame(), true };
    			Class[] paramsClass = {Frame.class, boolean.class};
    			IFilterWindow i = (IFilterWindow) Class.forName(f.getWindow()).getConstructor(paramsClass).newInstance(params);
    			i.setFilter(f);
    			i.setVisible(true);
    			Object[] row = { i.getFilter(), "Video" };
    			((DefaultTableModel)jTable1.getModel()).addRow(row);
    			i = null;
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
}//GEN-LAST:event_jComboBox2ActionPerformed

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
            int[] indexes = jTable1.getSelectedRows();
        	DefaultTableModel model = (DefaultTableModel) this.jTable1.getModel();
            for(int i=indexes.length - 1; i >= 0 ; i--){
            	model.removeRow(indexes[i]);
            }
        }
    }//GEN-LAST:event_jTable1KeyPressed

    private void saveProfile() {
    	Element root = new Element("Profile");
		Element el = new Element("Name");
		el.setText(jTextField1.getText());
		root.addContent(el);               
		
		Element video = new Element("VideoOptions");
		Element audio = new Element("AudioOptions");
		
		DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
		
		for(int i=0; i<model.getRowCount(); i++){
			if(((String)model.getValueAt(i, 1)).equals("Video")){
				el = new Element("VideoOption");
				el.setText(((Filter)model.getValueAt(i, 0)).toString());
				video.addContent(el);   
			} else if(((String)model.getValueAt(i, 1)).equals("Audio")){
				el = new Element("AudioOption");
				el.setText(((Filter)model.getValueAt(i, 0)).toString());
				audio.addContent(el);   
			} else {
				el = new Element("VideoOption");
				el.setText(((Filter)model.getValueAt(i, 0)).toString());
				video.addContent(el);   
				el = new Element("AudioOption");
				el.setText(((Filter)model.getValueAt(i, 0)).toString());
				audio.addContent(el);   				
			}
		}
		
		root.addContent(video);
		root.addContent(audio);
		
    	Document doc = new Document(root);
    	// serialize it onto System.out
    	try {
    		XMLOutputter serializer = new XMLOutputter();
    		Format f = serializer.getFormat();
    		f.setIndent("  ");
    		serializer.setFormat(f);
    		String name = "AviSynth" + "_" + jTextField1.getText() + ".xml";
    		File file = new File(name);
    		if(file.exists()){
    			name += this.hashCode();
    		}
    		FileWriter fileWriter = new FileWriter(DataModel.INSTANCE.getProfilesDir() + name);
    		serializer.output(doc, fileWriter);
    		fileWriter.flush();
    		fileWriter.close();
    	} catch (IOException e) {
    		System.err.println(e);
    	}
    }

    
    public void loadFilters(){
        String[] filters = DataModel.INSTANCE.loadFilters();
    	for(int i=0; i<filters.length; i++)
    		jComboBox2.addItem(filters[i]);
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FilterChainDialog dialog = new FilterChainDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration//GEN-END:variables

}
